package com.hundsun.cprs.yyt.web.action.area;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import com.hundsun.cprs.yyt.service.goods.domain.GoodsSpecs;
import com.hundsun.cprs.yyt.service.goods.domain.query.GoodsQuery;
import com.hundsun.cprs.yyt.service.goods.service.GoodsService;
import com.hundsun.cprs.yyt.service.goods.service.GoodsSkuService;
import com.hundsun.cprs.yyt.web.action.BaseAction;
import com.hundsun.cprs.yyt.web.vo.JsonModel;

@Controller
@RequestMapping("/area/stock")
public class StockAction extends BaseAction{
    
    @Autowired
    private GoodsService goodsService;
    
    @Autowired
    private GoodsSkuService skuService;

    @RequestMapping(value = "/stock_in",method=RequestMethod.GET)
    public String stockIn(String areaCode,ModelMap model){
        if (StringUtils.isNotEmpty(areaCode)) {
            GoodsQuery query = new GoodsQuery();
            query.setAreaCode(areaCode);
            model.put("goodsList", goodsService.queryGoodsByList(query));
        }
        model.put("stockFlag", 1);
        return "/area/stockLog/stock";
    }
    
    @RequestMapping(value = "/stock_out",method=RequestMethod.GET)
    public String stockOut(String areaCode,ModelMap model){
        if (StringUtils.isNotEmpty(areaCode)) {
            GoodsQuery query = new GoodsQuery();
            query.setAreaCode(areaCode);
            model.put("goodsList", goodsService.queryGoodsByList(query));
        }
        model.put("stockFlag", 0);
        return "/area/stockLog/stock";
    }
    
    @RequestMapping(value = "/stock",method=RequestMethod.POST)
    @ResponseBody
    public JsonModel stock(Long skuId,Integer stockFlag ,Integer stockNum){
        GoodsSpecs sku = skuService.selectByPrimaryKey(skuId);
        if (sku == null) {
            return new JsonModel(JsonModel.RESULD_CODE_FAIL,"商品规格不存在");
        }
        
        try {
            if (stockFlag == 1) {
                skuService.addGoodsStock(skuId, stockNum);
            } 
            if (stockFlag == 0) {
                skuService.deductGoodsStock(skuId, stockNum);
            }
        } catch (Exception e) {
            log.error("库存操作失败",e);
            return new JsonModel(JsonModel.RESULD_CODE_FAIL,"操作失败");
        }
        return new JsonModel(JsonModel.RESULD_CODE_SUCCESS,"成功");
    }
    
}
